import turtle as t
import random

food = [random.randint(-200, 200),  random.randint(-200, 200)]
ting = 0

def s():
    """
    画食物 蓝色小球
    :return: 
    """
    t.up()
    t.goto(food)
    t.down()
    t.dot(20, 'blue')


# 贪吃蛇的位置坐标
points = [[0, 0], [-20, 0], [-40, 0]]
# 控制蛇的移动  0 或1  改变的位置
index = 1
# 移动的值  +20   /  -20
value = 20

def draw():
    """
    绘制图形
    :return:
    """
    global index, value, ting
    t.clear()
    s()
    # 绘制蛇的点以及判断是否越界等操作
    for i in points:
        t.up()
        t.goto(i)
        t.down()
        t.dot(20, 'red')
        if i[0] < -300 or i[0] > 300:
            print(i[0])
            ting = 1
        if i[1] < -300 or i[1] > 300:
            print(i[1])
            ting = 1
    pos = points[0].copy()
    # 判断是否吃到食物， 如果吃到不移除最后一个 否则移除
    if abs(pos[0] - food[0]) < 20 and abs((pos[1] - food[1])) < 20:
        food[0] = random.randint(-200, 200)
        food[1] = random.randint(-200, 200)
    else:
        del points[-1]

    pos[index] += value
    points.insert(0, pos)
    if ting == 0 :
        t.ontimer(draw, 300)


t.tracer(False)


def func_up():
    """上键触发函数"""
    global index, value
    index = 1
    value = 20


def func_down():
    """下键触发函数"""
    global index, value
    index = 1
    value = -20


def func_right():
    """右键触发函数"""
    global index, value
    index = 0
    value = 20


def func_left():
    """左键触发函数"""
    global index, value
    index = 0
    value = -20


draw()

# 监听键盘上的上下左右按键
t.onkeypress(func_up, 'Up')
t.onkeypress(func_down, 'Down')
t.onkeypress(func_right, 'Right')
t.onkeypress(func_left, 'Left')
t.listen()

t.done()
